package main

import (
	"github.com/labstack/echo"
	"net/http"
	"strings"
    "os/user"
    "io/ioutil"
    "path"
    "log"
    "path/filepath"
    "github.com/shirou/gopsutil/process"
    "os"
    "fmt"
    "encoding/json"
)


var (
    Music_Dir = "H:/music"
)


type Song struct {
    Name string `json:"name"`
    Path string `json:"path"`
}

type MyConf struct {
    MusicDir string `json:"MusicDir"`
}

type Response struct {
	Code int `form:"code" json:"code" xml:"code"  binding:"required"`
    Msg string `form:"msg" json:"msg" xml:"msg"  binding:"required"`
    Songs []Song `form:"songs" json:"songs" xml:"songs"  binding:"required"`
}

func UserHome() string {
    var homepath string
    user, err := user.Current()
    if nil == err {
        homepath = user.HomeDir
    }
    return homepath
}


func init(){
    var mc MyConf
    conf := fmt.Sprintf("%v/music.conf",UserHome())
    confContent,err := ReadFile(conf)
    log.Println(string(confContent))
    if err != nil {
        return
    }
    jsErr := json.Unmarshal(confContent,&mc)
    if jsErr == nil{
        log.Println(mc.MusicDir)
        if mc.MusicDir != ""{
            Music_Dir = mc.MusicDir
        }
    } else{
        log.Println(jsErr)
    }
}



func ReadFile(filePath string) ([]byte,error) {
    var content []byte
    file, err := os.Open(filePath)
    if err != nil {
        return content,err
    }
    //func (f *File) Close() error {}
    defer file.Close()
    //func ReadAll(r io.Reader) ([]byte, error) {}
    content, err = ioutil.ReadAll(file)
    
    return content,nil
}
func ProcesToPid(name string) int32 {
    pids, _ := process.Pids()
    for _, pid := range pids {
        pn, _ := process.NewProcess(pid)
        pName, _ := pn.Name()
        if  strings.Contains(pName,name)  {
            return pid
        }
    }
    return -1
}


func GetMusic() ([]Song,error){
    var song_list []Song
    filepath.Walk(Music_Dir,func(pathDir string, f os.FileInfo, err error) error {
        if f == nil {
            return err
        }
        if f.IsDir() {
            fmt.Println("dir:", pathDir)
            return nil
        }

        
        
        var s Song
        fileSuffix := path.Ext(filepath.Base(pathDir))
        
        s.Name = strings.TrimSuffix(filepath.Base(pathDir), fileSuffix) 
        file_tmp := fmt.Sprintf("%v",strings.Split(pathDir,"music")[1])
        s.Path = strings.ReplaceAll(file_tmp,"\\","/")
        if fileSuffix == ".mp3"  {
            song_list = append(song_list,s)
        }
        
        return nil
    }) 


    return song_list,nil
}


func run() {
	e := echo.New()
	e.Static("/music", Music_Dir)
	e.GET("/getMyMusic", func(c echo.Context) error {
		c.Response().Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域
       	c.Response().Header().Set("Access-Control-Allow-Credentials", "true")
        mysong,err := GetMusic()
        if err != nil {
            return c.JSON(http.StatusOK, Response{-1,"获取音乐文件失败",mysong})
        }else{
            return c.JSON(http.StatusOK, Response{200,"已获取音乐",mysong})
        }
		
	})

	e.Logger.Fatal(e.Start(":1987"))
}

func main() {
	run()
}
